package v1

import (
	"fmt"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"ginblog/utils/validator"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

var code int


// 添加用户
func AddUser(c *gin.Context){
	// 引入结构体
	var data model.User
	var msg string
	_ = c.ShouldBindJSON(&data)

	msg,code = validator.Validate(&data)
	if code != errmsg.SUCCSE{
		c.JSON(http.StatusOK,gin.H{
			"status":code,
			"message":msg,
		})
		return
	}

	code = model.CheckUser(data.Username)
	if code == errmsg.SUCCSE{
		model.CreateUser(&data)
	}
	if code == errmsg.ERROR_USERNAME_USED {
		code = errmsg.ERROR_USERNAME_USED
	}

	c.JSON(http.StatusOK, gin.H{
		"status":code,
		"message":errmsg.GetErrorMsg(code),
	})

}


// 查询单个用户
// 查询用户列表
func GetUsers(c *gin.Context){
	pageSize,_ := strconv.Atoi(c.DefaultQuery("pagesize", "10"))
	pageNum,_ := strconv.Atoi(c.DefaultQuery("pagenum", "1"))
	uid,_ := c.Get("userid")
	fmt.Printf("uid666:%#v\n",uid)

	data,total := model.GetUsers(pageSize, pageNum)
	code = errmsg.SUCCSE
	c.JSON(http.StatusOK,gin.H{
		"status":code,
		"data":data,
		"total":total,
		"message":errmsg.GetErrorMsg(code),
	})
}


// 编辑用户
func EditUser(c *gin.Context){
	var data model.User
	id,_ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&data)
	code = model.CheckUser(data.Username)
	if code == errmsg.SUCCSE {
		model.EditUser(id, &data)
	}
	if code == errmsg.ERROR_USERNAME_USED{
		c.Abort()
	}

	c.JSON(http.StatusOK,gin.H{
		"status":code,
		"message":errmsg.GetErrorMsg(code),
	})
}


// 删除用户
func DeleteUser(c *gin.Context){
	id,_ := strconv.Atoi(c.Param("id"))

	code = model.DeleteUser(id)
	c.JSON(http.StatusOK,gin.H{
		"status":code,
		"message":errmsg.GetErrorMsg(code),
	})
}